package com.yuyang.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.constant.ProductConstants;
import com.yuyang.common.to.SkuHasStockTo;
import com.yuyang.common.to.SkuReductionTo;
import com.yuyang.common.to.SpuBoundsTo;
import com.yuyang.common.to.es.SkuEsModel;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;
import com.yuyang.common.utils.R;
import com.yuyang.gulimall.product.dao.SpuInfoDao;
import com.yuyang.gulimall.product.entity.*;
import com.yuyang.gulimall.product.feign.CouponFeignService;
import com.yuyang.gulimall.product.feign.SearchFeignService;
import com.yuyang.gulimall.product.feign.WareFeignService;
import com.yuyang.gulimall.product.service.*;
import com.yuyang.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByConditon(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        String status = (String) params.get("status");
        spuInfoEntityQueryWrapper.and(StringUtils.isNotBlank(key),
                        wrapper -> wrapper.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key)).
                eq(StringUtils.isNotBlank(brandId) && !"0".equals(brandId), SpuInfoEntity::getBrandId, brandId).
                eq(StringUtils.isNotBlank(catelogId) && !"0".equals(catelogId), SpuInfoEntity::getCatalogId, catelogId).
                eq(StringUtils.isNotBlank(status), SpuInfoEntity::getPublishStatus, status);

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void productUp(Long spuId) {
        //spu可检索的规格参数
        List<ProductAttrValueEntity> baseAttrs = attrService.baseAttrBySpuId(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchTypeAttrIds = attrService.getSearchTypeAttrIds(attrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(attr ->searchTypeAttrIds.contains(attr.getAttrId())).
                map(attr -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(attr, attrs);
                    return attrs;
                }).collect(Collectors.toList());

        List<SkuInfoEntity> skus = skuInfoService.getSkuListBySpuId(spuId);
        //TODO 1、远程调用库存服务，是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> booleanMap = null;
        try {
            R listR = wareFeignService.hasStockBySkuIds(skuIds);
            TypeReference<List<SkuHasStockTo>> typeReference = new TypeReference<List<SkuHasStockTo>>() {
            };
            booleanMap = listR.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询失败{}", e);
        }


        //2.封装每个sku的信息
        Map<Long, Boolean> finalBooleanMap = booleanMap;
        List<SkuEsModel> skuEsModels = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            //设置sku的图片
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            skuEsModel.setSkuPrice(sku.getPrice());
            //设置库存
            skuEsModel.setHasStock(finalBooleanMap != null ? finalBooleanMap.get(sku.getSkuId()) : false);

            //3.TODO 热度 hotScore
            skuEsModel.setHotScore(0L);
            //4.查询品牌的名称图片和分类的名称
            BrandEntity byId = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());

            skuEsModel.setCatalogName(categoryService.getById(skuEsModel.getCatalogId()).getName());
            //5.sku检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        //6、TODO 将数据发给es保存
        R r = searchFeignService.productStartUp(skuEsModels);
        if (r.getCode() == 0) {
            LambdaUpdateWrapper<SpuInfoEntity> updateWrapper = new LambdaUpdateWrapper<SpuInfoEntity>().
                    eq(SpuInfoEntity::getId, spuId).
                    set(SpuInfoEntity::getPublishStatus, ProductConstants.PublishStatusEnum.SPU_UP.getCode());
            this.update(updateWrapper);
        } else {
//            TODO 远程调用重试 接口的幂等性
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        return this.getOne(new LambdaQueryWrapper<SpuInfoEntity>().eq(SpuInfoEntity::getId, skuInfoEntity.getSpuId()));
    }


//    @GlobalTransactional 0.7版本不支持批量插入 TODO 暂未找到合适版本
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
//        1、保存spu的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();
//        2、保存spu的介绍信息 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        spuInfoDescService.saveDecript(spuId, decript);

//        3、spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImgs(spuId, images);
//        4、spu的 规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(spuId, baseAttrs);

//        5、spu的积分 gulimall_sms -> sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(spuSaveVo.getBounds(), spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() == 1) {
            log.error("spu的积分信息保存失败");
        }

//        6、保存sku的信息
        List<Skus> skus = spuSaveVo.getSkus();
        skus.forEach(sku -> {
            String defaultImg = "";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImg = image.getImgUrl();
                }
            }
//          6.1) sku的基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            if (sku.getDescar() != null) {
                skuInfoEntity.setSkuDesc(String.join(",", sku.getDescar()));
            }
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoService.save(skuInfoEntity);
            Long skuId = skuInfoEntity.getSkuId();

//          6.2) sku的图片 pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().
                    filter(img -> StringUtils.isNotBlank(img.getImgUrl())).
                    map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesEntity.setDefaultImg(img.getDefaultImg());
                        skuImagesEntity.setImgUrl(img.getImgUrl());
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

//          6.3) sku的销售属性 pms_sku_sale_attr_value
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

//          6.4) sku的满减、折扣、会员价格等  gulimall_sms ->sms_sku_ladder、sms_member_price、sms_sku_full_reduction
            if (sku.getFullCount() > 0 && sku.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                BigDecimal price = sku.getPrice().multiply(sku.getDiscount());
                skuReductionTo.setPrice(price);
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r1.getCode() == 1) {
                    log.error("sku的优惠信息保存失败");
                }
            }
        });
    }


}